import runtime, {
  async
} from '../../lib/runtime/runtime'
import request from '../../request/index'
import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from '../../utils/asyncWx'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    height: 0,
    cartList: [],
    allChecked: true,
    allPrice: 0,
    allNum: 0,
    address: {}, //用户地址
    payList: []
  },

  //获取收货地址
  async handleAddress() {
    try {
      //获取权限状态
      const res = await getSetting()
      const flag = res.authSetting["scope.address"]
      if (!flag) {
        //权限为false去设置权限
        await openSetting()
      }
      //获取地址
      let address = await chooseAddress()
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
      //本地缓存
      wx.setStorageSync("address", address);
    } catch (err) {
      console.log(err);
    }
  },
  //获取数据
  getData() {
    let address = wx.getStorageSync('address')
    let {
      payList
    } = this.data
    this.setData({
      address,
    })
    this.setCart(payList)
  },
  //价格计算
  setCart(cartList) {
    let {
      allPrice,
      allNum
    } = this.data
    //初始化数据
    allPrice = 0
    allNum = 0
    //判断每一项商品的选中状态
    cartList.forEach(x => {
      allPrice += x.num * x.goods_price
      allNum += x.num
    })
    this.setData({
      allNum,
      allPrice
    })
  },
  //点击结算
  async settlement() {
    const {
      address,
      allNum
    } = this.data
    //收货地址判断
    if (!address.userName) {
      await showToast('未选择收货地址')
      return
    }
    if (allNum === 0) {
      await showToast('未勾选商品')
      return
    }
    //跳转支付
    wx.navigateTo({
      url: '/pages/order/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取上一页面的传值
    let {
      payList
    } = this.data
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      payList = data.data
    })
    this.setData({
      payList
    })
    console.log(this.data.payList);
    let my_height = wx.getSystemInfoSync().windowHeight
    this.setData({
      height: my_height - 45 - 85 - 48
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData()
    console.log(this.data.cartList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})